package com.qd.p2p.web.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSONObject;
import com.qdlc.p2p.biz.service.AdditionalUserCardService;
import com.qdlc.p2p.biz.service.BindingCardService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.service.activity.usercard.UserCardExchangeStrategy;
import com.qdlc.p2p.biz.util.UserLoginUtil;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.enums.EnumCardType;
import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.dal.dto.AdditionalUserCard;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AdditionalUserCardModel;

/**
 * 用户卡片
 * @author linya 2016-01-06
 */
public class UserCardAction extends BaseAction<Object>{

	@Resource
	UserService userService;
	
	@Resource
	BindingCardService bindingCardService;
	
	@Resource
	AdditionalUserCardService additionalUserCardService;
	
	@Resource
	@Qualifier("userCardWineExchangeStrategy")
	UserCardExchangeStrategy userCardWineExchangeStrategy;
	
	/**
	 * [用户卡片] 获取用户卡状态
	 */
	@Action(value="/member/usercard/list")
	public void userCardList() throws Exception {
		User user = UserLoginUtil.getLoginUser();
		AdditionalUserCardModel model = new AdditionalUserCardModel();
		model.setUserId(user.getUserId());
		//获取用户卡
		List<AdditionalUserCard> list = additionalUserCardService.findUserCards(user.getUserId(), null);
		JSONObject jsonObject = new JSONObject();
		if(list != null){
			for(AdditionalUserCard card: list){
				EnumCardType cardType = EnumCardType.getCardType(card.getType());
				if(cardType != null){
					jsonObject.put(cardType.name().toLowerCase(), card.getId());
				}
			}
		}
        printWebJson(getStringOfJpaObj(jsonObject));
	}
	
	/**
	 * [用户卡片] 兑换"酒"、"掌"、"柜"卡片
	 * @return
	 */
	@Action(value="/member/usercard/exchange/wine")
	public void addBank() throws Exception {
		User user = UserLoginUtil.getLoginUser();
		String cardIds = paramString("cardIds");
		if(StringUtils.isBlank(cardIds)){
			printWebResult("请选择需要兑换的卡片", false);
		}
		
		String[] cardIdStr = cardIds.split(",");
		long[] cardIdLong = new long[cardIdStr.length];
		for(int i = 0; i < cardIdStr.length; i ++){
			cardIdLong[i] = DataUtils.toInt(cardIdStr[i]);
		}
		
		ReturnResult result = userCardWineExchangeStrategy.exchange(user, cardIdLong);
		printWebResult(result.getErrorInfo(), result.isSuccess());
		
	}
	
}
